﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.ComponentModel;
using System.Data;
using WooYang.Data.Attributes;

namespace WooYang.Data.DataBase
{
    public class ReaderVSModel
    {
        public static T ToModel<T>(DbDataReader reader, object item)
        {
            Type type = item.GetType();
            int count = reader.FieldCount;
            for (int i = 0; i < count; i++)
            {
                string PropertyName = reader.GetName(i);
                object value = reader.GetValue(i);
                foreach (System.ComponentModel.PropertyDescriptor property in TypeDescriptor.GetProperties(type))
                {
                    string name = property.Name;
                    if (name.ToLower()==PropertyName.ToLower()&& value.GetType() != typeof(DBNull) && !property.IsReadOnly)
                    {
                        property.SetValue(item, value);
                        break;
                    }
                }

            }
            return (T)item;
        }
        public static IEnumerable<T> ToEnumerable<T>(DataTable dt) {
            var propertes=TypeDescriptor.GetProperties(typeof(T));
            if (dt.Rows.Count>0)
            {
                foreach (DataRow item in dt.Rows)
                {
                    T model =(T) Activator.CreateInstance(typeof(T));
                    foreach (System.ComponentModel.PropertyDescriptor property in propertes)
                    {
                        string name =property.Name ;
                        var k = property.Attributes[typeof(DBMapAttribute)];
                        if (k != null)
                            name = k.ToString();
                        if (item[name] != null && item[name].GetType() != typeof(DBNull) && !property.IsReadOnly)
                        {
                            property.SetValue(model, item[property.Name]);
                        }
                    }
                    yield return model;
                }
            }
        }
    }
}
